<?php

namespace App\Repositories;

trait BaseRepository
{
    /**
     * Get number of records.
     *
     * @return array
     */
    public function getNumber()
    {
        $total = $this->model->count();

        $new = $this->model->whereSeen(0)->count();

        return compact('total', 'new');
    }
    
    /**
     * @param string $column
     * @param int $num
     * @param int $id
     * @return number
     */
    public function increment($column,$num,$id)
    {
        $model = $this->model->withTrashed()->find($id);
        
        return $model->increment($column,$num);
    }

    /**
     * @param string $column
     * @param int $num
     * @param int $id
     * @return number
     */
    public function decrement($column,$num,$id)
    {
        $model = $this->model->find($id);
        
        return $model->decrement($column,$num);
    }
    /**
     * Destroy a model.
     *
     * @param int $id
     */
    public function destroy($id)
    {
        $this->getById($id)->delete();
    }

    /**
     * Get Model by id.
     *
     * @param int $id
     *
     * @return App\Models\Model
     */
    public function getById($id,$with = '')
    {
        if($with)
            return $this->model->withTrashed()->with($with)->find($id);
        else 
            return $this->model->find($id);
    }
    
    /**
     *  
     */
    public function getByIds($ids)
    {
        return $this->model->whereIn('id',$ids)->get();
    }
    
    public function getByAttr($attr)
    {
        return $this->model->where($attr)->first();
    }

    /**
     * 根据不同字段取值
     */
    public function getByKey($key = 'parent_id', $val = 0)
    {
        return $this->model->where([$key => $val])->get();
    }
    
    public function isExists($companyId,$needId)
    {
        return $this->model->where(['company_id'=>$companyId,'need_id'=>$needId])->first();
    }
    
    public function getByKeyFirst($key = 'parent_id', $val = 0, $with='')
    {
        if(isset($with) && !empty($with)) {
            return $this->model->with($with)->where([$key => $val])->first();
        }else{
            return $this->model->where([$key => $val])->first();
        }
    }    
    
    /**
     * 批量插入数据 
     */
    public function batchInsert($input)
    {
        return $this->model->insert($input);
    }
}
